from odoo import fields, models, api
from odoo.exceptions import UserError


class RESSequenceCode(models.Model):
    _name = 'res.sequence.code'
    _description = '序列号'
    _sql_constraints = [('unique_name', 'UNIQUE(code)', '名称必须唯一'),
                        ('unique_prefix', 'UNIQUE(model_id,prefix)', '同一个模型中，序列号必须唯一')]
    _rec_name = 'code'

    code = fields.Char(string='编号', default='RP_SQC/***', copy=False, index=True)
    model_id = fields.Many2one(string='关联模型', comodel_name='ir.model')

    prefix = fields.Char(string='前缀', required=True)
    index = fields.Integer(string='索引', default=1, required=True)
    padding = fields.Integer(string='位数(零填充)', default=3, required=True)

    key = fields.Char(string='键')
    value = fields.Char(string='值')

    @api.model_create_multi
    def create(self, vals):
        for val in vals:
            val['code'] = self.env['ir.sequence'].sudo().next_by_code('res.sequence.code') or '/'
        return super(RESSequenceCode, self).create(vals)
